#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2024/4/3 14:23
# @File    : demo01.py
# @Description : -i http://pypi.tuna.tsinghua.edu.cn/simple/ --trusted-host pypi.tuna.tsinghua.edu.cn


from tksheet import Sheet
import tkinter as tk


# 自定义右键

class demo(tk.Tk):
    def __init__(self):
        tk.Tk.__init__(self)
        self.grid_columnconfigure(0, weight = 1)
        self.grid_rowconfigure(0, weight = 1)
        self.frame = tk.Frame(self)
        self.frame.grid_columnconfigure(0, weight = 1)
        self.frame.grid_rowconfigure(0, weight = 1)
        self.sheet = Sheet(self.frame,
                           show_row_index=False, # 关闭索引
                           show_top_left=False, # 关闭左上角全选区域
                           data = [[f"Row {r}, Column {c}\nnewline1\nnewline2" for c in range(10)] for r in range(20)])
        self.sheet.enable_bindings(
                          "single_select",
                                   "drag_select",
                                   #"edit_cell",
                                   #"select_all",
                                   "column_select",
                                   #"row_select",
                                   "column_width_resize",
                                   "double_click_column_resize",
                                   "arrowkeys",
                                   "row_height_resize",
                                   "double_click_row_resize",
                                   "right_click_popup_menu",
                                   #"rc_select"
        )
        self.sheet.extra_bindings([("begin_edit_cell", self.begin_edit_cell),
                                   ("end_edit_cell", self.end_edit_cell)])

        #self.sheet.close_index_dropdown(0)
        self.sheet.column_width(column=0, width=20, only_set_if_too_small=False, redraw=True)
        self.sheet.row_index()

        #self.sheet.change_theme(theme = "dark", redraw = True)

        self.sheet.highlight_rows(rows=[0], bg='yellow', fg=None)
        self.sheet.highlight_cells(row=1, column=1, bg='yellow', fg=None)

        # 滚动或查看到对应的行数
        self.sheet.see(row=5, column=0)

        def on_mouse_move(event):
            # 获取鼠标在 tksheet 中的位置
            x, y = event.x, event.y
            # print(event.widget)
            # 每个单元格的宽高（这里默认认为每个单元格的宽高都一致）
            row_wide = self.sheet.get_column_widths()[0]
            row_height = self.sheet.get_row_heights()[0]
            # 计算鼠标当前所在的行（注意要减去表头的高度，如果有的话）
            row, col = y // row_height, x // row_wide
            print(row, col)
            # 检查行号是否在有效范围内
            if 0 <= row < self.sheet.get_row_heights().__len__():
                # 清除之前所有行的背景颜色
                self.sheet.dehighlight_rows(rows=[], redraw=True)
                # 为当前行加背景颜色, 发现问题带滚动条时 定位会失败
                self.sheet.highlight_rows(rows=[row], bg='#E6EFFD', fg=None)

        self.sheet.bind("<Motion>", on_mouse_move)

        self.sheet.popup_menu_add_command("Say Hello", self.new_right_click_button)
        self.frame.grid(row = 0, column = 0, sticky = "nswe")
        self.sheet.grid(row = 0, column = 0, sticky = "nswe")

    def new_right_click_button(self, event = None):
        print ("Hello World!")

    def begin_edit_cell(self, event = None):
        return event.text

    def end_edit_cell(self, event = None):
        # remove spaces from user input
        if event.text is not None:
            return event.text.replace(" ", "")

#
app = demo()
app.mainloop()

